<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
	xmlns:th="http://www.thymeleaf.org">

<head th:include="head :: htmlhead" th:with="title='协议生成管理'"></head>

<!-- <link rel=stylesheet href="../codemirror/doc/docs.css"> -->
<!-- codemirror核心css -->
<link rel="stylesheet" href="../codemirror/lib/codemirror.css">
<!-- <link rel="stylesheet" href="../codemirror/addon/fold/foldgutter.css"> -->
<!-- <link rel="stylesheet" href="../codemirror/addon/dialog/dialog.css"> -->
<link rel="stylesheet" href="../codemirror/theme/monokai.css">
<link rel="stylesheet" href="../codemirror/addon/hint/show-hint.css">
<!-- codemirror核心js -->
<script src="../codemirror/lib/codemirror.js"></script>
<script src="../codemirror/addon/search/searchcursor.js"></script>
<script src="../codemirror/addon/search/search.js"></script>
<script src="../codemirror/addon/dialog/dialog.js"></script>
<script src="../codemirror/addon/edit/matchbrackets.js"></script>
<script src="../codemirror/addon/edit/closebrackets.js"></script>
<!-- <script src="../codemirror/addon/comment/comment.js"></script> -->
<!-- <script src="../codemirror/addon/wrap/hardwrap.js"></script> -->
<!-- <script src="../codemirror/addon/fold/foldcode.js"></script> -->
<!-- <script src="../codemirror/addon/fold/brace-fold.js"></script> -->
<!-- 语言类型 -->
<script src="../codemirror/mode/javascript/javascript.js"></script>
<script src="../codemirror/mode/clike/clike.js"></script>
<script src="../codemirror/keymap/sublime.js"></script>
<script src="../codemirror/addon/hint/show-hint.js"></script>
<script src="../codemirror/addon/hint/anyword-hint.js"></script>

<!-- 编辑模板页 -->
<body>
<form class="layui-form" action="">

  <div class="layui-form-item">
  	<div class="layui-inline">
  	<input type="text" id="fileName" name="fileName" lay-verify="title" autocomplete="off" placeholder="输入协议文件名" class="layui-input">
  	</div>
  	 <div class="layui-inline">
     <button id="submit" class="layui-btn" lay-submit lay-filter="runTemplate">Run</button>
     </div>
<!--      <div class="layui-inline"> -->
<!--      <button id="submit" class="layui-btn" lay-submit lay-filter="saveTemplate">Save</button> -->
<!--      </div> -->
	<div class="layui-inline">
     <button id="saveButton" type="button" class="layui-btn">Save</button>
     </div>
     <div class="layui-inline">
     <button id="button" type="button" class="layui-btn" >Clear</button>
     </div>
  </div>
  
<div style="margin: 0 auto;">
 <div class="layui-row">
    <div class="layui-col-md2">
      <div class="grid-demo">
      	<div id="test9" class="demo-tree demo-tree-box" ></div>
      </div>
    </div>
    <div class="layui-col-md5 ">
      <div class="grid-demo grid-demo-bg1">
      		<textarea class="form-control" id="code" name="code"></textarea>
      </div>
    </div>
    <div class="layui-col-md5">
      <div class="grid-demo grid-demo-bg1">
      		<textarea class="form-control" id="show" name="show"></textarea>
      </div>
    </div>
  </div>
</div>
</form>

<script type="text/javascript"  th:inline="none">
//根据DOM元素的id构造出一个展示器
var shower = CodeMirror.fromTextArea(document.getElementById("show"), {
    mode: "text/x-java", //实现java代码高亮
    lineNumbers: true,	//显示行号
    theme: "monokai",	//设置主题
    lineWrapping: true,	//代码折叠
    foldGutter: true,
    gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
    matchBrackets: true,	//括号匹配
//     keyMap: "sublime",		//键盘映射
    autoCloseBrackets: true,//开启花括号补全
    showCursorWhenSelecting: true,//选中显示鼠标
    tabSize: 2, 				//tab空格数量
    readOnly: true       //只读
});
shower.setSize('auto', '710');     //设置代码框的长宽
// shower.setValue("");    //先代码框的值清空

//根据DOM元素的id构造出一个编辑器
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
    mode: "text/x-custom", //实现自定义模式
    lineNumbers: true,	//显示行号
    theme: "monokai",	//设置主题
    lineWrapping: true,	//代码折叠
    foldGutter: true,
    gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
    matchBrackets: true,	//括号匹配
    keyMap: "sublime",		//键盘映射
    autoCloseBrackets: true,//开启花括号补全
    showCursorWhenSelecting: true,//选中显示鼠标
    tabSize: 2,				//tab空格数量
    hintOptions: { // 自定义提示选项
        completeSingle: false, // 当匹配只有一项的时候是否自动补全
    }
})
editor.on('change', editor => {
	//shower.setValue(editor.getValue());
    $("#code").text(editor.getValue());
});
editor.on('keypress', () => {
	//编译器内容更改事件
    editor.showHint();
});
editor.setValue("");
editor.setSize('auto', '710px');     //设置代码框的长宽
//操作系统判断
var mac = CodeMirror.keyMap.default == CodeMirror.keyMap.macDefault;
CodeMirror.keyMap.default[(mac ? "Cmd" : "Ctrl")] = "autocomplete";
//anyword autocomplete
CodeMirror.commands.autocomplete = function(cm) {
  cm.showHint({hint: CodeMirror.hint.anyword});
}
setTimeout(() => {
   this.editor.refresh();
   this.shower.refresh();
},100);//让编辑器每次在调用的时候进行自动刷新

//表单操作
var curNode = 0;
layui.use(function(){
    var form = layui.form;
    var tree = layui.tree;
    form.on('submit(runTemplate)', function (data) {
        var e = data.field.code;
        $.ajax({
            type: 'POST',
            url: '/zproto/module/runTemplate',
            data: e,
            dataType: 'JSON',
            contentType: "application/json; charset=utf-8",
            success: function(data){
                var str = data.tips;
                shower.setValue(data.data);
                if(data.code == 0){
                	layer.msg(str, {icon: 1});
                }else{
                	layer.msg(str, {icon: 2});
                }
            },
//             error: function(jqXHR){console.log(jqXHR)},
        });
        return false;
	});
//     form.on('submit(saveTemplate)', function (data) {
//     	var d = {};
//     	d.curNode = curNode;
//         d.fileName = data.field.fileName;
//         d.content = data.field.code;
//         $.ajax({
//             type: 'POST',
//             url: '/zproto/module/updateTemplateDetail',
//             data: JSON.stringify(d),
//             dataType: 'JSON',
//             contentType: "application/json; charset=utf-8",
//             success: function(data){
//                 var str = data.tips;
//                 if(data.code == 0){
//                 	layer.msg(str, {icon: 1});
//                 }else{
//                 	layer.msg(str, {icon: 2});
//                 }
//             },
// //             error: function(jqXHR){console.log(jqXHR)},
//         });
//         return false;
// 	});
    $.ajax({
        type: "post",
        url: "/zproto/setting/templateFileList",
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        async: true,//是否异步请求
        success: function (data) {
            layui.use('tree', function () {
                var tree = layui.tree;
                var data1 = data.data;
                //templateTreeRender(tree, data.data);
              	//开启节点操作图标
                tree.render({
                  elem: '#test9'
                  ,data: data1
                  ,accordion: true//开启手风琴模式
                  ,showLine:false
                  //,onlyIconControl: true  //是否仅允许节点左侧图标控制展开收缩
                  ,edit: ['update', 'del'] //操作节点的图标
                  ,click: function(obj){
                	//如果数据为空, 直接获取后台数据
                	//如果数据不为空, 询问后获取后台数据
                	if(curNode == obj.data.id){
                		return;
                	}
                	if(obj.data.id < 1000){
                		return;
                	}
           	    	var val = editor.getValue();
           	    	var d = {};
           	    	d.curNode = obj.data.id;
           	        d.fileName = obj.data.title;
           	    	if (val !=""){
           	    		layer.confirm('检测已存在编辑内容, 确定要覆盖为新内容吗?', function(index){
           	                layer.close(index);
           	                showTemplateDetail(d);
           	             	curNode = obj.data.id;
           	            });
           	    	}else{
           	    		showTemplateDetail(d);
           	    		curNode = obj.data.id;
           	    	}
           	      }
                ,operate: function(obj){
                    var type = obj.type; //得到操作类型：add、edit、del
                    var data = obj.data; //得到当前节点的数据
                    var elem = obj.elem; //得到当前节点元素
//                     if(type === 'add'){ //修改节点
//                     	var dto = {}
//                         dto.curNode = data.id;
//                     	newTemplateFile(dto);
//                     }
                    if(type === 'update'){ //修改节点
                      var dto = {}
                      dto.curNode = data.id;
                      dto.fileName = data.title;
                      renameTemplateFile(dto);
                    } else if(type === 'del'){ //删除节点
                    	var dto = {}
                        dto.curNode = data.id;
                        dto.fileName = data.title;
                        deleteTemplateFile(dto)
                    };
                  }
                });
              	//tree end
            })
        }
    })
});

//抽出通用方法
function showTemplateDetail(dto){
     $.ajax({
         type: 'POST',
         url: '/zproto/module/showTemplateDetail',
         data: JSON.stringify(dto),
         dataType: 'JSON',
         contentType: "application/json; charset=utf-8",
         success: function(data){
             editor.setValue(data.data);
             if(data.code == 0){
            	 $("input[name='fileName']").val(dto.fileName);
             }
         },
         error : function(data) {
             alert("访问出错！");
             return false;
         }
     });
}

//清空功能
$("#button").click(function(){
	 editor.setValue("");
	 shower.setValue("");
	 $("input[name='fileName']").val("");
});

$("#saveButton").click(function(){
	 var fileName = $("#fileName").val();
	 var content = $("#code").val();
	 //文件名或文件编号无数据, 表示新增文件
	 if(fileName == "" || curNode == 0){
		 //同步更新缓存对应的值
         layer.open({
             type: 2 //此处以iframe举例
             ,title: '新增模板'
             ,area: ['450px', '300px']
             ,shade: 0
             ,maxmin: true
             ,offset: [ //为了演示，随机坐标
                 0
                 ,0
             ]
             ,content:"/zproto/setting/addTemplateView"
             ,zIndex: layer.zIndex //重点1
             ,success: function(layero, index){
                 layer.setTop(layero); //重点2
                 var body = layer.getChildFrame('body', index);
                 var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                 //console.log(body.html()); //得到iframe页的body内容
                 body.find("textarea[name='content']").val(content);
             }
         });
	 }else{
		 $("form").submit();
	 }
  }); 

$("form").submit(function(e){
	var d = {};
	d.curNode = curNode;
    d.fileName = $("#fileName").val();
    d.content = $("#code").val();
    $.ajax({
        type: 'POST',
        url: '/zproto/module/updateTemplateDetail',
        data: JSON.stringify(d),
        dataType: 'JSON',
        contentType: "application/json; charset=utf-8",
        success: function(data){
            var str = data.tips;
            if(data.code == 0){
            	layer.msg(str, {icon: 1});
            }else{
            	layer.msg(str, {icon: 2});
            }
        },
        error: function(jqXHR){console.log(jqXHR)},
    });
    return false;
});

//删除模板文件
function deleteTemplateFile(dto){
     $.ajax({
         type: 'POST',
         url: '/zproto/module/deleteTemplateFile',
         data: JSON.stringify(dto),
         dataType: 'JSON',
         contentType: "application/json; charset=utf-8",
         success: function(data){
        	 var str = data.tips;
        	 if(data.code == 0){
             	layer.msg(str, {icon: 1});
             }else{
             	layer.msg(str, {icon: 2});
             }
         },
         error : function(data) {
             alert("访问出错！");
             return false;
         }
     });
}

//改名模板文件
function renameTemplateFile(dto){
     $.ajax({
         type: 'POST',
         url: '/zproto/module/renameTemplateFile',
         data: JSON.stringify(dto),
         dataType: 'JSON',
         contentType: "application/json; charset=utf-8",
         success: function(data){
        	 var str = data.tips;
        	 if(data.code == 0){
             	layer.msg(str, {icon: 1});
             }else{
             	layer.msg(str, {icon: 2});
             }
         },
         error : function(data) {
             alert("访问出错！");
             return false;
         }
     });
}

// //新建模板文件
// function newTemplateFile(dto){
//      $.ajax({
//          type: 'POST',
//          url: '/zproto/module/newTemplateFile',
//          data: JSON.stringify(dto),
//          dataType: 'JSON',
//          contentType: "application/json; charset=utf-8",
//          success: function(data){
//         	 var str = data.tips;
//         	 console.log("====>"+data.data); //得到iframe页的body内容
//         	 if(data.code == 0){
//              	layer.msg(str, {icon: 1});
//              }else{
//              	layer.msg(str, {icon: 2});
//              }
//          },
//          error : function(data) {
//              alert("访问出错！");
//              return 0;
//          }
//      });
// }

</script>

</body>
</html>
